package services

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/support/collect"

	"goravel/app/models"
)

type MenuService struct {
}

func (r *MenuService) MenuWithRole(ctx http.Context, adminId int) ([]models.Menu, error) {
	var admin models.Admin
	err := facades.Orm().Query().Model(models.Admin{}).Where("id = ?", adminId).With("Roles").With("Roles.Menus").Find(&admin)
	if err != nil {
		return nil, err
	}
	menus := make([]models.Menu, 0)
	collect.Each(admin.Roles, func(role models.Role, _ int) {
		collect.Each(role.Menus, func(menu models.Menu, _ int) {
			menus = append(menus, menu)
		})
	})
	tree := r.buildTree(menus, 0)
	return tree, nil
}

func (r *MenuService) buildTree(list []models.Menu, parentId uint) []models.Menu {

	tree := make([]models.Menu, 0)
	collect.Each(list, func(item models.Menu, _ int) {
		if item.ParentId == parentId {
			item.Children = r.buildTree(list, item.ID)
			tree = append(tree, item)
		}
	})
	return tree
}
